<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"xuarmy.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="木を植える一番いい時間は十年前、次は今です。">
<meta property="og:type" content="website">
<meta property="og:title" content="代号·破局">
<meta property="og:url" content="http://xuarmy.gitee.io/blog/index.html">
<meta property="og:site_name" content="代号·破局">
<meta property="og:description" content="木を植える一番いい時間は十年前、次は今です。">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="xuarmy">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://xuarmy.gitee.io/blog/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>代号·破局</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">代号·破局</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">学无先后·达者为先</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://xuarmy.gitee.io/blog/2020/08/14/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/photo.jpg">
      <meta itemprop="name" content="xuarmy">
      <meta itemprop="description" content="木を植える一番いい時間は十年前、次は今です。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="代号·破局">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2020/08/14/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/" class="post-title-link" itemprop="url">iOS - 单例模式</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-08-14 22:26:23 / 修改时间：22:32:38" itemprop="dateCreated datePublished" datetime="2020-08-14T22:26:23+08:00">2020-08-14</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="1-单例模式"><a href="#1-单例模式" class="headerlink" title="1. 单例模式"></a>1. 单例模式</h1><h2 id="1-1-单例简介"><a href="#1-1-单例简介" class="headerlink" title="1.1. 单例简介"></a>1.1. 单例简介</h2><p>单例模式可以保证在整个应用程序运行过程中，一个类只有一个实例，共享一份资源。易于供外界访问，方便控制，节约系统资源，一般用于工具类。例如：登陆控制器，网络数据请求等。</p>
<h2 id="1-2-单例特点"><a href="#1-2-单例特点" class="headerlink" title="1.2. 单例特点"></a>1.2. 单例特点</h2><ul>
<li><p><strong>单例的优点</strong></p>
<blockquote>
<p>1.保证系统中一个类只有一个实例，该实例易于外界访问，方便对实例个数的控制并节约系统资源。<br>2.保证局部变量永远只初始化一次，在程序运行过程中，永远只有一分内存。</p>
</blockquote>
</li>
<li><p><strong>单例的缺点</strong></p>
<blockquote>
<p>1.单例的对象一旦建立，对象指针保存在静态区的，在堆中分配的内存空间，在应用程序终止后才会被释放。<br>2.单例无法继承，因为静态变量也会继承，当子类和父类同时创建的时只会创建一个先创建的实例对象，很难进行类的扩展。<br>3.单例的对象不适用于变化，如果同一类型的对象总是要在不同的用例场景发生变化，单例就会引起数据的错误，不能保存彼此的状态。</p>
</blockquote>
</li>
</ul>
<p><strong>注意：</strong>我们在使用单例类时，一定要考虑好单例类是否适合，和类以后的扩展性，避免滥用单例。</p>
<h1 id="2-iOS常用的单例类"><a href="#2-iOS常用的单例类" class="headerlink" title="2. iOS常用的单例类"></a>2. iOS常用的单例类</h1><table>
<thead>
<tr>
<th>类别</th>
<th>简介</th>
<th>Object-C示例</th>
<th>Swift示例</th>
</tr>
</thead>
<tbody><tr>
<td><code>UIApplication</code></td>
<td>应用程序</td>
<td><code>[UIApplication sharedApplication]</code></td>
<td><code>UIApplication.shared</code></td>
</tr>
<tr>
<td><code>NSNotificationCenter</code></td>
<td>消息中心</td>
<td><code>[NSNotificationCenter defaultCenter]</code></td>
<td><code>NotificationCenter.default</code></td>
</tr>
<tr>
<td><code>NSFileManager</code></td>
<td>文件管理</td>
<td><code>[NSFileManager defaultManager]</code></td>
<td><code>FileManager.default</code></td>
</tr>
<tr>
<td><code>NSUserDefaults</code></td>
<td>偏好设置</td>
<td><code>[NSUserDefaults standardUserDefaults]</code></td>
<td><code>UserDefaults.standard</code></td>
</tr>
<tr>
<td><code>NSURLCache</code></td>
<td>请求缓存</td>
<td><code>[NSURLCache sharedURLCache]</code></td>
<td><code>URLCache.shared</code></td>
</tr>
<tr>
<td><code>NSHTTPCookieStorage</code></td>
<td>Cookie池</td>
<td><code>[NSHTTPCookieStorage sharedHTTPCookieStorage]</code></td>
<td><code>HTTPCookieStorage.shared</code></td>
</tr>
<tr>
<td><code>NSURLSession</code></td>
<td>网络请求</td>
<td><code>[NSURLSession sharedSession]</code></td>
<td><code>URLSession.shared</code></td>
</tr>
<tr>
<td><code>UIMenuController</code></td>
<td>菜单栏</td>
<td><code>[UIMenuController sharedMenuController]</code></td>
<td><code>UIMenuController.shared</code></td>
</tr>
</tbody></table>
<h1 id="3-单例的实现"><a href="#3-单例的实现" class="headerlink" title="3. 单例的实现"></a>3. 单例的实现</h1><p><strong>Obejct-C代码示例</strong></p>
<p>简单写法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">+ (instancetype)sharedInstance &#123;</span><br><span class="line">  static XATestManager* instance &#x3D; nil;</span><br><span class="line">  static dispatch_once_t onceToken;</span><br><span class="line">  dispatch_once(&amp;onceToken, ^&#123;</span><br><span class="line">    instance &#x3D; [[XATestManager alloc] init];</span><br><span class="line">  &#125;);</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>严谨写法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;XATestManager.h&quot;</span><br><span class="line">static XATestManager *instance;</span><br><span class="line"></span><br><span class="line">@implementation XATestManager</span><br><span class="line">&#x2F;&#x2F;给外部提供的类方法</span><br><span class="line">+ (instancetype)shareInstance &#123;</span><br><span class="line">    static dispatch_once_t onceToken;</span><br><span class="line">    dispatch_once(&amp;onceToken, ^&#123;</span><br><span class="line">        instance &#x3D; [[XATestManager alloc] init];</span><br><span class="line">    &#125;);</span><br><span class="line">    </span><br><span class="line">    return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;实例化分配内存</span><br><span class="line">+ (instancetype)allocWithZone:(struct _NSZone *)zone &#123;</span><br><span class="line">    static dispatch_once_t onceToken;</span><br><span class="line">    dispatch_once(&amp;onceToken, ^&#123;</span><br><span class="line">        instance &#x3D; [super allocWithZone:zone];</span><br><span class="line">    &#125;);</span><br><span class="line">    </span><br><span class="line">    return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;实现copy协议</span><br><span class="line">-(id)copyWithZone:(NSZone *)zone &#123;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (id)mutableCopyWithZone:(nullable NSZone *)zone &#123;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (id)copy &#123;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">-(id)mutableCopy &#123;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>加互斥锁解决多线程访问安全的写法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;XATestManager.h&quot;</span><br><span class="line">static XATestManager *instance;</span><br><span class="line"></span><br><span class="line">@implementation XATestManager</span><br><span class="line">&#x2F;&#x2F;给外部提供的类方法</span><br><span class="line">+ (instancetype)shareInstance &#123;</span><br><span class="line">  @synchronized (self) &#123;</span><br><span class="line">    if (instance &#x3D;&#x3D; nil) &#123;</span><br><span class="line">      instance &#x3D; [[XATestManager alloc] init];</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;实例化分配内存</span><br><span class="line">+ (instancetype)allocWithZone:(struct _NSZone *)zone &#123;</span><br><span class="line">  @synchronized (self) &#123;</span><br><span class="line">    if (instance &#x3D;&#x3D; nil) &#123;</span><br><span class="line">      instance &#x3D; [super allocWithZone:zone];</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;实现copy协议</span><br><span class="line">-(id)copyWithZone:(NSZone *)zone &#123;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (id)mutableCopyWithZone:(nullable NSZone *)zone &#123;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (id)copy &#123;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">-(id)mutableCopy &#123;</span><br><span class="line">  return instance;</span><br><span class="line">&#125;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>



<p><strong>Swift代码示例</strong></p>
<p>可以使用静态类型属性创建简单的单例，即使在多个线程同时访问时，也可以保证仅对它们进行一次惰性初始化：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XATestManager</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">let</span> sharedInstance = <span class="type">XATestManager</span>()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果需要执行初始化以外的其他设置，则可以将闭包的调用结果分配给全局常量：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XATestManager</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">let</span> sharedInstance: <span class="type">XATestManager</span> = &#123;</span><br><span class="line">        <span class="keyword">let</span> instance = <span class="type">XATestManager</span>()</span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">        <span class="keyword">return</span> instance</span><br><span class="line">    &#125;()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>参考链接: <a target="_blank" rel="noopener" href="https://developer.apple.com/documentation/swift/cocoa_design_patterns/managing_a_shared_resource_using_a_singleton">Apple Inc.</a></p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://xuarmy.gitee.io/blog/2020/08/10/%E4%BB%A3%E7%90%86%E5%9B%9E%E8%B0%83%E9%80%9A%E7%9F%A5%E7%9B%91%E5%90%AC/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/photo.jpg">
      <meta itemprop="name" content="xuarmy">
      <meta itemprop="description" content="木を植える一番いい時間は十年前、次は今です。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="代号·破局">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2020/08/10/%E4%BB%A3%E7%90%86%E5%9B%9E%E8%B0%83%E9%80%9A%E7%9F%A5%E7%9B%91%E5%90%AC/" class="post-title-link" itemprop="url">iOS - 委托、回调、通知、监听</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-08-10 20:33:40 / 修改时间：20:41:49" itemprop="dateCreated datePublished" datetime="2020-08-10T20:33:40+08:00">2020-08-10</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="1-委托-Delegate"><a href="#1-委托-Delegate" class="headerlink" title="1. 委托 - Delegate"></a>1. 委托 - Delegate</h1><h2 id="1-1-Delegate简介"><a href="#1-1-Delegate简介" class="headerlink" title="1.1. Delegate简介"></a>1.1. Delegate简介</h2><p>在Object-C语法中没有多继承的，在很多时候需要使用到协议<code>protocol</code>。协议的实现有关的东西—-委托代理<code>delegate</code>。<br>委托是两个对象协同解决问题，主要分为两种，一种是，一个对象为对另一个对象中的变化提供数据，如：<code>NSTableViewDataSource</code>；另一个是，一个对象响应另一个对象的行为，如：<code>NSTableViewDelegate</code>。</p>
<p>委托主要有两个部分委托和代理，这两部分协同工作。</p>
<table>
<thead>
<tr>
<th align="center">委托方</th>
<th align="center">代理方</th>
</tr>
</thead>
<tbody><tr>
<td align="center">a.定义协议</td>
<td align="center">a.遵守协议</td>
</tr>
<tr>
<td align="center">b.声明遵守协议的属性</td>
<td align="center">b.设置遵守代理的属性</td>
</tr>
<tr>
<td align="center">c.代理调用协议</td>
<td align="center">c.实现协议方法</td>
</tr>
</tbody></table>
<h2 id="1-2-Delegate特点"><a href="#1-2-Delegate特点" class="headerlink" title="1.2. Delegate特点"></a>1.2. Delegate特点</h2><ul>
<li><p><strong>委托（Delegate）的优点</strong></p>
<blockquote>
<p>1.语法严格，响应的事件必须在协议中有清晰的定义。<br>2.逻辑清晰，没有要求保持/监视通信过程，流程可跟踪，出了问题后方便定位错误。<br>3.可以接受协议方法的返回值，delegate能够反馈信息给controller。<br>4.减少代码的耦合性，分离事件的监听和处理。</p>
</blockquote>
</li>
<li><p><strong>委托（Delegate）的缺点</strong></p>
<blockquote>
<p>1.需要编写的代码比较多: a.协议定义；b.delegate属性声明；c.delegate调用；d.实现delegate方法。<br>2.释放delegate属性，<code>delegate = nil</code>再调用容易引起程序crash。<br>3.跨层传值的场合，增加代码的耦合性，容易使代码的层次结构将变的混乱。<br>4.书写错误容易引起循环引用</p>
</blockquote>
</li>
</ul>
<h2 id="1-3-Delegate代码示例"><a href="#1-3-Delegate代码示例" class="headerlink" title="1.3. Delegate代码示例"></a>1.3. Delegate代码示例</h2><h3 id="Object-C代码示例"><a href="#Object-C代码示例" class="headerlink" title="Object-C代码示例"></a>Object-C代码示例</h3><p>定义<code>Delegate</code>的代码，在<code>XATestVCA</code>中实现如下</p>
<p>1、委托对象的实现有两种方式：一种是<code>@required</code> <strong>- 必须实现</strong>，一种是<code>@optional</code> <strong>- 可选实现</strong>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">@protocol XATestVCADelegate&lt;NSObject&gt;</span><br><span class="line">@optional - (void)didTouchTestButton:(NSInteger)tag;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>2、在<code>XATestVCA</code>中包含一个委托对象的弱引用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">@interface XATestVCA : UIViewController</span><br><span class="line">@property (nonatomic, weak, nullable) id&lt;XATestVCADelegate&gt; delegate;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>3、调用委托方法的时机。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">- (void)onTouchTestButton:(UIButton *)sender &#123;</span><br><span class="line">  &#x2F;&#x2F; 确定委托是否存</span><br><span class="line">  if (self.delegate !&#x3D; nil &amp;&amp; [self.delegate respondsToSelector:@selector(didTouchTestButton:)]) &#123;</span><br><span class="line">    &#x2F;&#x2F; 调用委托方法</span><br><span class="line">    [delegate didTouchTestButton:sender.tag];</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现<code>Delegate</code>的代码，在<code>XATestVCB</code>中实现如下</p>
<p>4、通过<code>setDelegate:(id)object</code>实现委托的调用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@interface XATestVCB : UIViewController, XATestVCADelegate</span><br><span class="line">@end</span><br><span class="line">@implementation XATestVCB</span><br><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">  [super viewDidLoad];</span><br><span class="line">  XATestVCA *testVCA &#x3D; [[XATestVCA alloc] init]</span><br><span class="line">  testVCA.delegate &#x3D; self;</span><br><span class="line">&#125;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>5、实现委托的方法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- (void)didTouchTestButton:(NSInteger)tag &#123;</span><br><span class="line">    &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Swift代码示例"><a href="#Swift代码示例" class="headerlink" title="Swift代码示例"></a><strong>Swift代码示例</strong></h3><p>定义<code>Delegate</code>的代码，在<code>XATestVCA</code>中实现如下</p>
<p>1、<code>@optional</code>和<code>@required</code>是<code>Objective-C</code>中特有的关键字。<code>Swift</code>中，默认所有方法都是必须实现的。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">XATestVCBDelegate</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">func</span> <span class="title">didTouchTestButton</span><span class="params">(<span class="number">_</span> tag: Int)</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>Swift</code>中，协议里方法不可以直接定义<code>optional</code>关键字，解决方法如下:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@objc</span> <span class="class"><span class="keyword">protocol</span> <span class="title">XATestVCADelegate</span> </span>&#123;</span><br><span class="line">  <span class="meta">@objc</span> <span class="keyword">optional</span> <span class="function"><span class="keyword">func</span> <span class="title">didTouchTestButton</span><span class="params">(<span class="number">_</span> tag: Int)</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2、在<code>XATestVCA</code>中包含一个委托对象：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XATestVCA</span>: <span class="title">UIViewController</span> </span>&#123;</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">var</span> delegate: <span class="type">XATestVCADelegate?</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3、调用委托方法的时机。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@objc</span> <span class="keyword">private</span> <span class="function"><span class="keyword">func</span> <span class="title">onTouchTestButton</span><span class="params">(<span class="number">_</span> sender: UIButton)</span></span> &#123;</span><br><span class="line">  <span class="keyword">if</span> delegate != <span class="literal">nil</span> &#123;</span><br><span class="line">    delegate?.didTouchTestButton(button.tag)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现<code>Delegate</code>的代码，在<code>XATestVCB</code>中实现如下</p>
<p>4、通过<code>setDelegate:(id)object</code>实现委托的调用。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XATestVCB</span>: <span class="title">UIViewController</span>, <span class="title">XATestDelegate</span> </span>&#123;</span><br><span class="line">  <span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidLoad</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">super</span>.viewDidLoad() </span><br><span class="line">    <span class="keyword">let</span> testAVC = <span class="type">XATestVCA</span>()</span><br><span class="line">    testAVC.delegate = <span class="keyword">self</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>5、实现委托的方法。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">didTouchTestButton</span><span class="params">(<span class="number">_</span> tag: Int)</span></span> &#123;  </span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>



<h1 id="2-回调-Block"><a href="#2-回调-Block" class="headerlink" title="2. 回调 - Block"></a>2. 回调 - Block</h1><h2 id="2-1-Block简介"><a href="#2-1-Block简介" class="headerlink" title="2.1. Block简介"></a>2.1. Block简介</h2><p>Block是iOS 4.0、macOS 10.6以后引进的对语言的扩展。Block是对象，它封装了一段代码，这段代码可以在任何时候执行。Block可以作为函数参数或者函数的返回值，也可以带输入参数或返回值。Block写法更简练，不需要写protocol、函数，采用Block语法，提高了代码的可读性，可维护性，封装性。</p>
<h2 id="2-2-Block特点"><a href="#2-2-Block特点" class="headerlink" title="2.2. Block特点"></a>2.2. Block特点</h2><ul>
<li><p><strong>Block的优点</strong></p>
<blockquote>
<p>1.Block属于代码块，语法严格代码逻辑清晰。<br>2.语法简洁，代码更为紧凑，代码的可读性强</p>
</blockquote>
</li>
<li><p><strong>Block的缺点</strong></p>
<blockquote>
<p>1.Block内默认引用为强引用，容易造成循环引用。<br>2.线程同步性不好控制。</p>
</blockquote>
</li>
</ul>
<p><strong>注意：</strong><br>1.循环引用问题，如果block里用了self，需要替换为</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">__weak typeof(self) weakSelf &#x3D; self;</span><br></pre></td></tr></table></figure>

<h2 id="2-3-Block代码示例"><a href="#2-3-Block代码示例" class="headerlink" title="2.3. Block代码示例"></a>2.3. Block代码示例</h2><h3 id="Object-C代码示例-1"><a href="#Object-C代码示例-1" class="headerlink" title="Object-C代码示例"></a>Object-C代码示例</h3><p>如果用block进行两个类之间的互动，需要这样：<br>BLOCK首先你在.h文件中声明BLOCK对象，当然返回的参数你可以自己定义：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">typedef void (^TouchTestButtonBlock)(NSInteger tag);</span><br></pre></td></tr></table></figure>

<p>在.m文件中执行时：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">@interface XATestVCA : UIViewController</span><br><span class="line">@property (nonatomic, copy) TouchTestButtonBlock blockProerty;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>其他类执行block时是这样的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- (void)onTouchTestButton:(UIButton *)sender &#123;</span><br><span class="line">  if (self.blockProerty !&#x3D; nil) &#123;</span><br><span class="line">    self.blockProerty(sender.tag);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其他类执行block时是这样的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@implementation XATestVCB : UIViewController</span><br><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">  [super viewDidLoad];</span><br><span class="line">  XATestVCA *vca &#x3D; [[XATestVCA alloc] init];</span><br><span class="line">  vca.blockProerty &#x3D; ^(NSInteger tag) &#123;</span><br><span class="line">    &#x2F;&#x2F; TODO:</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<h3 id="Swift代码示例-1"><a href="#Swift代码示例-1" class="headerlink" title="Swift代码示例"></a>Swift代码示例</h3><p>定义<code>Block</code>的代码，在<code>XATestVCA</code>中实现如下</p>
<p>1、<code>@optional</code>和<code>@required</code>是<code>Objective-C</code>中特有的关键字。<code>Swift</code>中，默认所有方法都是必须实现的。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定义block</span></span><br><span class="line"><span class="keyword">typealias</span> <span class="type">TouchTestButtonBlock</span> = (<span class="type">Int</span>) -&gt;()</span><br></pre></td></tr></table></figure>

<p>2、通常是在对象主体包含一个委托对象的弱引用：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XATestVCA</span>: <span class="title">UIViewController</span> </span>&#123;</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">var</span> blockProerty: <span class="type">TouchTestButtonBlock!</span></span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<p>3、判断触发回调方法。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@objc</span> <span class="keyword">private</span> <span class="function"><span class="keyword">func</span> <span class="title">onTouchTestButton</span><span class="params">(<span class="number">_</span> sender: UIButton)</span></span> &#123;</span><br><span class="line">  <span class="keyword">if</span> <span class="keyword">let</span> <span class="number">_</span> = blockProerty &#123;</span><br><span class="line">    blockProerty(sender.tag)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现<code>Block</code>的代码，在<code>XATestVCB</code>中实现如下</p>
<p>4、连接对象主体和委托，通过setDelegate:(id)obj来实现。如果实现委托的类有委托需要的方法就执行方法。大概就是这样。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XATestVCB</span>: <span class="title">UIViewController</span> </span>&#123;</span><br><span class="line">  <span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidLoad</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">super</span>.viewDidLoad()</span><br><span class="line">    <span class="keyword">let</span> vca = <span class="type">XATestVCA</span>()</span><br><span class="line">    vca.blockProerty = &#123; (tag) <span class="keyword">in</span></span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">    &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="3-通知-Notification"><a href="#3-通知-Notification" class="headerlink" title="3. 通知 - Notification"></a>3. 通知 - Notification</h1><h2 id="3-1-Notification简介"><a href="#3-1-Notification简介" class="headerlink" title="3.1. Notification简介"></a>3.1. Notification简介</h2><p>Notification是负责对象之间的通信，通过单例对象<code>NSNotificationCenter</code>注册观察对象、并发送消息通知。发送对象和接收对象是一对多的关系，通知是多播<code>multiCast</code>形式。向非特定的多个对象发送消息称之为广播<code>broadcast</code>.</p>
<h2 id="3-2-Notification特点"><a href="#3-2-Notification特点" class="headerlink" title="3.2. Notification特点"></a>3.2. Notification特点</h2><ul>
<li><p>Notification的优点</p>
<blockquote>
<p>1.一个对象发出的通知，多个对象可以进行响应，是一对多的方式。<br>2.传值方便快捷，不显示数量和类型。</p>
</blockquote>
</li>
<li><p>Notification的缺点</p>
<blockquote>
<p>1.释放注册的对象时候，需要在通知中心取消注册，否则将出现不可预见的crash<br>2.代码出现问题时不易调试，代码流程难跟踪<br>3.通知发出后，发出通知的对象不能从观察者处获得任何反馈。<br>4.大量定义notificationWithName容易代码混乱，可以写成宏定义文件统一管理。</p>
</blockquote>
</li>
</ul>
<h2 id="3-3-Notification代码示例"><a href="#3-3-Notification代码示例" class="headerlink" title="3.3. Notification代码示例"></a>3.3. Notification代码示例</h2><h3 id="Objec-C代码示例"><a href="#Objec-C代码示例" class="headerlink" title="Objec-C代码示例"></a>Objec-C代码示例</h3><ol>
<li>注册观察者</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendTestMessage:) name:@&quot;testNotification&quot; object:nil];</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>发送通知</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[[NSNotificationCenter defaultCenter] postNotificationName:@&quot;testNotification&quot; object:self userInfo:@&#123;@&quot;key&quot;:@&quot;value&quot;&#125;];</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>收到通知</li>
</ol>
<p><code>XATestVCB.h</code>文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">@interface XATestVCB :NSObject</span><br><span class="line">- (void)sendTestMessage:(NSNotification *)notification;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p><code>XATestVCB.m</code>文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@implementation XATestVCB</span><br><span class="line">- (void)sendTestMessage:(NSNotification *)notification &#123;</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p><strong>注意：</strong>可以跟一个参数，但是只能是NSNotification对象。</p>
<ol start="4">
<li>移除观察者</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[[NSNotificationCenter defaultCenter] removeObserver:self name:@&quot;testNotification&quot; object:nil];</span><br></pre></td></tr></table></figure>

<h3 id="Swift代码示例-2"><a href="#Swift代码示例-2" class="headerlink" title="Swift代码示例"></a>Swift代码示例</h3><ol>
<li>注册观察者</li>
</ol>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NotificationCenter</span>.<span class="keyword">default</span>.addObserver(<span class="keyword">self</span>, selector: #selector(sendTestMessage(<span class="number">_</span>:)), name: <span class="type">NSNotification</span>.<span class="type">Name</span>(rawValue: <span class="string">&quot;testNotification&quot;</span>), object: <span class="literal">nil</span>)</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>发送通知</li>
</ol>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NotificationCenter</span>.<span class="keyword">default</span>.post(name: <span class="type">NSNotification</span>.<span class="type">Name</span>(rawValue: <span class="string">&quot;testNotification&quot;</span>), object: <span class="keyword">self</span>, userInfo: [<span class="string">&quot;key&quot;</span>: <span class="string">&quot;value&quot;</span>])</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>收到通知</li>
</ol>
<p><code>XATestVCB.swift</code>文件：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XATestVCB</span>: <span class="title">NSObject</span> </span>&#123;</span><br><span class="line">  <span class="keyword">open</span> <span class="meta">@objc</span> <span class="function"><span class="keyword">func</span> <span class="title">sendTestMessage</span><span class="params">(<span class="number">_</span> notification:NSNotification)</span></span> &#123;</span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">    <span class="keyword">let</span> userInfo = notification.userInfo</span><br><span class="line">    <span class="keyword">let</span> object = notification.object</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意：</strong>可以跟一个参数，但是只能是NSNotification对象。</p>
<ol start="4">
<li>移除观察者</li>
</ol>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NotificationCenter</span>.<span class="keyword">default</span>.removeObserver(<span class="keyword">self</span>, name: <span class="type">NSNotification</span>.<span class="type">Name</span>(rawValue: <span class="string">&quot;testNotification&quot;</span>), object: <span class="literal">nil</span>)</span><br></pre></td></tr></table></figure>

<p><strong>参数说明</strong></p>
<p><strong>aName</strong></p>
<p><code>aName</code>是名称，定义一个类型为<code>NSNotification.Name</code>的全局常量，或者扩展<code>NSNotification.Name</code>即可。为了预防字符串重复，保持<code>rawValue</code>和常量名一致即可。例如:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> testNotificationName = <span class="type">Notification</span>.<span class="type">Name</span>(rawValue: <span class="string">&quot;testNotificationName&quot;</span>)</span><br></pre></td></tr></table></figure>

<p>通知发送后，所有观察<code>testNotificationName</code>的对象都会收到。</p>
<p><strong>object</strong></p>
<p><code>object</code>一般是在哪个类中调用<code>post</code>方法，就传哪个类，也可以传递参数。</p>
<p><strong>userInfo</strong></p>
<p><code>userInfo</code>传参数的字段，传递<code>[AnyHashable : Any]</code>字典类型。</p>
<h1 id="4-监听-KVO"><a href="#4-监听-KVO" class="headerlink" title="4. 监听 - KVO"></a>4. 监听 - KVO</h1><h2 id="4-1-KVO简介"><a href="#4-1-KVO简介" class="headerlink" title="4.1. KVO简介"></a>4.1. KVO简介</h2><p>KVO一种键值观察者模式，利用键值观察可以注册成为一个对象的观察者，在该对象的某个属性变化时收到通知。适合任何对象监听另一个对象的改变，使其一个对象与另外一个对象保持同步的一种方法。KVO只能对属性做出反应，不会用来对方法或者动作做出反应。<br>编写键值观察分为以下三步：a.注册成为观察者。b.定义KVO的回调。c.移除观察者。</p>
<h2 id="4-2-KVO特点"><a href="#4-2-KVO特点" class="headerlink" title="4.2. KVO特点"></a>4.2. KVO特点</h2><ul>
<li><p><strong>KVO的优点</strong></p>
<blockquote>
<p>1.提供一个简单地方法来实现两个对象的同步。<br>2.可以响应非自己创建对象（如系统控件），并且不改变对象内部的实现。<br>3.可以观察的属性变更前后的先前值和最新值。<br>4.代码量少，处理逻辑简单。</p>
</blockquote>
</li>
<li><p><strong>KVO的缺点</strong></p>
<blockquote>
<p>1.观察的属性必须使用string来定义，因此编译器不会出现警告和检查<br>2.iOS14对非公开属性（内部私有属性）观察，APP会发生crash</p>
</blockquote>
</li>
</ul>
<h2 id="4-3-KVO代码示例"><a href="#4-3-KVO代码示例" class="headerlink" title="4.3. KVO代码示例"></a>4.3. KVO代码示例</h2><h3 id="Object-C代码示例-2"><a href="#Object-C代码示例-2" class="headerlink" title="Object-C代码示例"></a>Object-C代码示例</h3><p>1.新建一个属性为<code>label</code>作为被观察者。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">@interface XATestVCA: UIViewController</span><br><span class="line">@property (nonatomic, copy) UILabel *label;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>2.给<code>label</code>添加一个观察者，这里是<code>XATestVCA</code>对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@implementation XATestVCA: UIViewController</span><br><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">  [super viewDidLoad];</span><br><span class="line">  &#x2F;&#x2F;建立观察者模式关系,注册观察者</span><br><span class="line">  [label addObserver:self forKeyPath:@&quot;text&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; </span><br><span class="line">&#125;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p><strong>参数说明</strong></p>
<table>
<thead>
<tr>
<th align="center">Num</th>
<th align="center">参数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">第一个参数</td>
<td align="center">NSObject</td>
<td><code>label</code>被观察者</td>
</tr>
<tr>
<td align="center">第二个参数</td>
<td align="center">observer</td>
<td><code>self</code>观察者，在观察者类中实现键值的观察方法</td>
</tr>
<tr>
<td align="center">第三个参数</td>
<td align="center">keyPath</td>
<td>forKeyPath键路径参数，要观察的键路径，这里观察<code>text</code></td>
</tr>
<tr>
<td align="center">第四个参数</td>
<td align="center">options</td>
<td>options标识键值如何变化传递给观察者，可以使用<code>,</code>进行多选，这里观察变化的新值和旧值。</td>
</tr>
<tr>
<td align="center">第五个参数</td>
<td align="center">context</td>
<td>上下文内存区，通常为<code>nil</code></td>
</tr>
</tbody></table>
<p>3.KVO的回调，实现键值的观察方法(必须实现)。change是一个字典，key值为<code>NSKeyValueChangeKey</code>枚举类型。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context &#123;</span><br><span class="line">    id oldValue &#x3D; [change objectForKey:NSKeyValueChangeOldKey];</span><br><span class="line">    id newValue &#x3D; [change objectForKey:NSKeyValueChangeNewKey];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.移除观察者</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- (void)dealloc &#123;</span><br><span class="line">  [label removeObserver:self forKeyPath:@&quot;text&quot;];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Swift代码示例-3"><a href="#Swift代码示例-3" class="headerlink" title="Swift代码示例"></a>Swift代码示例</h3><p>1.新建一个属性为<code>label</code>作为被观察者。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">weak</span> <span class="keyword">var</span> label: <span class="type">UILabel?</span></span><br></pre></td></tr></table></figure>

<p>2.给<code>label</code>添加一个观察者，这里是<code>XATestVCA</code>对象</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">XATestVCA</span>: <span class="title">UIViewController</span> </span>&#123;</span><br><span class="line">  <span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidLoad</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">super</span>.viewDidLoad()</span><br><span class="line">    label?.addObserver(<span class="keyword">self</span>, forKeyPath: <span class="string">&quot;text&quot;</span>, options: [.new,.old], context: <span class="literal">nil</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3.KVO的回调，实现键值的观察方法(必须实现)。change是一个字典，key值为<code>NSKeyValueChangeKey</code>枚举类型。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="class"><span class="keyword">class</span> <span class="title">func</span> <span class="title">observeValue</span>(<span class="title">forKeyPath</span> <span class="title">keyPath</span>: <span class="title">String</span>?, <span class="title">of</span> <span class="title">object</span>: <span class="title">Any</span>?, <span class="title">change</span>: [<span class="title">NSKeyValueChangeKey</span> : <span class="title">Any</span>]?, <span class="title">context</span>: <span class="title">UnsafeMutableRawPointer</span>?) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> oldValue = change?.index(forKey: .oldKey)</span><br><span class="line">  <span class="keyword">let</span> newValue = change?.index(forKey: .newKey)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.移除观察者</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">deinit</span> &#123;</span><br><span class="line">  label?.removeObserver(<span class="keyword">self</span>, forKeyPath: <span class="string">&quot;text&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="5-总结"><a href="#5-总结" class="headerlink" title="5. 总结"></a>5. 总结</h1><p>以上4中设计模式，都有各自的优点和缺点。其实世间万物都是这样，关键是如何选择。<strong>任何一种模式都没有对和错之分，只有更适合或者不适合一说，存在即有理。</strong></p>
<p><strong>Delegate</strong>:一对一的处理逻辑，早前iOS开发最常用的<code>controller</code>间通信方式。</p>
<p><strong>Block</strong>:使用场合与Delegate基本相同，代码块清晰，近年来使用较多。注意，大量嵌套使用Block会导致数据不同步，对象丢失等问题。</p>
<p><strong>Notification</strong>:应用中很多controller都需要知道一件事情的场合。不要过分的使用通知模式，否则后期代码维护工作量很大。</p>
<p><strong>KVO</strong>:对系统控件属性值改变使用场合较多，不需要改变控件原始代码。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://xuarmy.gitee.io/blog/2020/08/04/UIViewController%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/photo.jpg">
      <meta itemprop="name" content="xuarmy">
      <meta itemprop="description" content="木を植える一番いい時間は十年前、次は今です。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="代号·破局">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2020/08/04/UIViewController%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/" class="post-title-link" itemprop="url">UIViewController的生命周期</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-08-04 20:40:41 / 修改时间：21:05:23" itemprop="dateCreated datePublished" datetime="2020-08-04T20:40:41+08:00">2020-08-04</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="1-视图创建-初始化"><a href="#1-视图创建-初始化" class="headerlink" title="1. 视图创建/初始化"></a>1. 视图创建/初始化</h1><h2 id="1-1-xib创建UIViewController"><a href="#1-1-xib创建UIViewController" class="headerlink" title="1.1. xib创建UIViewController"></a>1.1. xib创建UIViewController</h2><p>通过xib文件创建<code>UIViewController</code>会调用这个方法。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil &#123;</span><br><span class="line">  if (self &#x3D; [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) &#123;</span><br><span class="line">    &#x2F;&#x2F; TODO:</span><br><span class="line">  &#125;</span><br><span class="line">  return self;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="keyword">init</span>(nibName nibNameOrNil: <span class="type">String?</span>, bundle nibBundleOrNil: <span class="type">Bundle?</span>) &#123;</span><br><span class="line">  <span class="keyword">super</span>.<span class="keyword">init</span>(nibName: nibNameOrNil, bundle: nibBundleOrNil)</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="1-2-StoryBoard串联图"><a href="#1-2-StoryBoard串联图" class="headerlink" title="1.2. StoryBoard串联图"></a>1.2. StoryBoard串联图</h2><p>使用<code>StoryBoard</code>串联视图管理，程序不会直接初始化一个<code>UIViewController</code>，<code>StoryBoard</code>会自动初始化并调用<code>initWithCoder</code>。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">- (instancetype)initWithCoder:(NSCoder *)aDecoder &#123;</span><br><span class="line">    if (self &#x3D; [super initWithCoder:aDecoder]) &#123;</span><br><span class="line">    &#x2F;&#x2F; TODO:</span><br><span class="line">   &#125;</span><br><span class="line">  return self;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">required</span> <span class="keyword">init</span>?(coder: <span class="type">NSCoder</span>) &#123;</span><br><span class="line">  <span class="keyword">super</span>.<span class="keyword">init</span>(coder: coder)</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="2-视图加载"><a href="#2-视图加载" class="headerlink" title="2. 视图加载"></a>2. 视图加载</h1><h2 id="2-1-xib-storyboard-文件加载完了"><a href="#2-1-xib-storyboard-文件加载完了" class="headerlink" title="2.1. xib(storyboard)文件加载完了"></a>2.1. xib(storyboard)文件加载完了</h2><p>这个方法是，配合上述两个视图控制器实例化方法使用的，如果有些特殊需求，需要根据实际情况进行内容的设置，不能在<code>xib</code>或<code>storyBoard</code>中加载的内容，就可以在<code>awakeFromNib</code>方法中进行加载。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (void)awakeFromNib &#123;</span><br><span class="line">  [super awakeFromNib];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="class"><span class="keyword">class</span> <span class="title">func</span> <span class="title">awakeFromNib</span>() </span>&#123;</span><br><span class="line">  <span class="keyword">super</span>.awakeFromNib()</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-2-加载视图"><a href="#2-2-加载视图" class="headerlink" title="2.2. 加载视图"></a>2.2. 加载视图</h2><p>当<code>UIViewController</code>的<code>view</code>被访问且<code>view = nil</code>的时候，调用<code>loadView</code>方法。所以<code>loadView</code>方法在视图控制器的生命周期内可能会被多次调用（大多数情况只调用一次）。Apple对该API解释的时候强调<code>loadView</code>方法永远不要直接调用，而是由系统自动调用。<br>调用方法会加载或创建一个<code>view</code>并把它赋值给<code>UIViewController</code>的<code>view</code>。<br>在创建<code>view</code>的时，首先会根据<code>nibName</code>加载<code>nib</code>文件。如果<code>nibName</code>为空或找不到对应的<code>nib</code>文件，则会创建一个空视图（纯代码编写的场合）。  </p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- (void)loadView &#123;</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">loadView</span><span class="params">()</span></span> &#123;</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意</strong>  </p>
<ul>
<li>永远不要直接调用这个方法（系统自动调用）</li>
<li>重写这个方法的时候不要调用父类的该方法</li>
</ul>
<h2 id="2-3-视图加载完成"><a href="#2-3-视图加载完成" class="headerlink" title="2.3. 视图加载完成"></a>2.3. 视图加载完成</h2><p>当<code>loadView</code>将<code>view</code>载入内存中，会调用<code>viewDidLoad</code>方法，对视图来进行设置。比如：数据载入、初始设定、修改约束、隐藏视图、移除视图等。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">  [super viewDidLoad];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidLoad</span><span class="params">()</span></span> &#123;</span><br><span class="line">  <span class="keyword">super</span>.viewDidLoad()</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-4-视图将要出现"><a href="#2-4-视图将要出现" class="headerlink" title="2.4. 视图将要出现"></a>2.4. 视图将要出现</h2><p>系统内容载入所有数据后，将要在屏幕上显示视图时，调用这个方法，对即将显示的视图做进一步的设置。比如：根据设备方向修改视图的约束、设置视图显示样式、更新数据等。<br>在视图切换时，视图的每次将要重新显示，该方法都会被调用（<code>push</code>压栈的下一级视图<code>pop</code>出栈后，重新回到该视图时）。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (void)viewWillAppear:(BOOL)animated &#123;</span><br><span class="line">  [super viewWillAppear:animated];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewWillAppear</span><span class="params">(<span class="number">_</span> animated: Bool)</span></span> &#123;</span><br><span class="line">  <span class="keyword">super</span>.viewWillAppear(animated)</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-5-子视图将要布局"><a href="#2-5-子视图将要布局" class="headerlink" title="2.5. 子视图将要布局"></a>2.5. 子视图将要布局</h2><p><code>view</code> 将要布局<code>Subviews</code>。比如：<code>view</code>的<code>bounds</code>改变（状态栏显示/隐藏，视图方向等变化）后，调整<code>Subviews</code>的布局前，要做的工作在该方法中处理。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (void)viewWillLayoutSubviews &#123;</span><br><span class="line">  [super viewWillLayoutSubviews];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewWillLayoutSubviews</span><span class="params">()</span></span> &#123;</span><br><span class="line">  <span class="keyword">super</span>.viewWillLayoutSubviews()</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-6-子视图布局完成"><a href="#2-6-子视图布局完成" class="headerlink" title="2.6. 子视图布局完成"></a>2.6. 子视图布局完成</h2><p><code>view</code> 完成<code>Subviews</code>布局。比如：<code>view</code>的<code>bounds</code>改变（状态栏显示/隐藏，视图方向等变化）后，调整<code>Subviews</code>的布局完成后，要做的工作在该方法中处理。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (void)viewDidLayoutSubviews &#123;</span><br><span class="line">  [super viewDidLayoutSubviews];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidLayoutSubviews</span><span class="params">()</span></span> &#123;</span><br><span class="line">  <span class="keyword">super</span>.viewDidLayoutSubviews()</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-7-视图已经显示"><a href="#2-7-视图已经显示" class="headerlink" title="2.7. 视图已经显示"></a>2.7. 视图已经显示</h2><p>已经在屏幕上显示视图时，调用这个方法，对正在显示的视图做进一步的设置。比如：视图展示效果（动画）的处理。<br>在视图切换时，视图的每次重新显示完了，该方法都会被调用（<code>push</code>压栈的下一级视图<code>pop</code>出栈后，重新回到该视图时）。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (void)viewDidAppear:(BOOL)animated &#123;</span><br><span class="line">  [super viewDidAppear:animated];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidAppear</span><span class="params">(<span class="number">_</span> animated: Bool)</span></span> &#123;</span><br><span class="line">  <span class="keyword">super</span>.viewDidAppear(animated)</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="3-视图卸载"><a href="#3-视图卸载" class="headerlink" title="3. 视图卸载"></a>3. 视图卸载</h1><h2 id="3-1-视图将要消失"><a href="#3-1-视图将要消失" class="headerlink" title="3.1. 视图将要消失"></a>3.1. 视图将要消失</h2><p>在视图切换时，视图即将被移除时调用该方法。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (void)viewWillDisappear:(BOOL)animated &#123;</span><br><span class="line">  [super viewWillDisappear:animated];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewWillDisappear</span><span class="params">(<span class="number">_</span> animated: Bool)</span></span> &#123;</span><br><span class="line">  <span class="keyword">super</span>.viewWillDisappear(animated)</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3-2-视图已经消失"><a href="#3-2-视图已经消失" class="headerlink" title="3.2.视图已经消失"></a>3.2.视图已经消失</h2><p>在视图切换时，视图已经被移除后调用该方法。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (void)viewDidDisappear:(BOOL)animated &#123;</span><br><span class="line">  [super viewDidDisappear:animated];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">viewDidDisappear</span><span class="params">(<span class="number">_</span> animated: Bool)</span></span> &#123;</span><br><span class="line">  <span class="keyword">super</span>.viewDidDisappear(animated)</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="4-视图销毁"><a href="#4-视图销毁" class="headerlink" title="4. 视图销毁"></a>4. 视图销毁</h1><p>视图被销毁后调用该方法，比如：释放<code>init</code>和<code>viewDidLoad</code>中创建的对象。ARC的场合通常是：移除通知观察者、移除委托引用、<code>NSTimer</code>销毁、单类的其他操作等。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- (void)dealloc &#123;</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">deinit</span> &#123;</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="5-其他"><a href="#5-其他" class="headerlink" title="5. 其他"></a>5. 其他</h1><h2 id="5-1-内存警告"><a href="#5-1-内存警告" class="headerlink" title="5.1. 内存警告"></a>5.1. 内存警告</h2><p>当<code>app</code>可用内存过低时，系统发出内存警告调用该方法。比如：内存中存放的缓存数据和当前不显示的视图等。</p>
<p>Objec-C代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">- (void)didReceiveMemoryWarning &#123;</span><br><span class="line">  [super didReceiveMemoryWarning];</span><br><span class="line">  &#x2F;&#x2F; TODO:</span><br><span class="line">  if (self.isViewLoaded &amp;&amp; !self.view.window) &#123;</span><br><span class="line">    self.view &#x3D; nil;&#x2F;&#x2F; 目的是让视图重新加载时调用viewDidLoad</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Swift代码示例</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">func</span> <span class="title">didReceiveMemoryWarning</span><span class="params">()</span></span> &#123;</span><br><span class="line">  <span class="keyword">super</span>.didReceiveMemoryWarning()</span><br><span class="line">  <span class="comment">// <span class="doctag">TODO:</span></span></span><br><span class="line">  <span class="keyword">if</span> isViewLoaded &amp;&amp; (view.window != <span class="literal">nil</span>) &#123;</span><br><span class="line">    view = <span class="literal">nil</span> <span class="comment">// 目的是让视图重新加载时调用viewDidLoad</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>备考</strong></p>
<p>Debug内存警告：<code>Simulator</code>→<code>Debug</code>→<code>Simulate Memory Warning</code>（快捷键：<code>Shift</code>+<code>command</code>+<code>M</code>）</p>
<h1 id="6-总结"><a href="#6-总结" class="headerlink" title="6. 总结"></a>6. 总结</h1><ul>
<li>上述所有方法中只有<code>initWithNibName</code>方法需要手动调用，其他方法只需要重写即可。</li>
<li>上述所有方法中只有<code>initWithNibName</code>和<code>awakeFromNib</code>方法为处理视图控制器，其他方法都是处理视图。并且这两个方法在视图控制器的生命周期里只会被调用一次。</li>
<li>上述所有方法中<code>viewDidLoad</code>、<code>viewWillAppear</code>和<code>viewDidAppear</code>3个方法经常使用到。在处理视图切换时通常<code>viewDidLoad</code>方法只会调用一次，刷新数据等处理需要在<code>viewWillAppear</code>和<code>viewDidAppear</code>2个方法中处理。</li>
<li><code>didReceiveMemoryWarning</code>方法调用后不会调用<code>dealloc</code>方法，<code>didReceiveMemoryWarning</code>方法中如果不能释放内存，多次被调用后App会直接crash。</li>
</ul>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://xuarmy.gitee.io/blog/2020/08/01/hello-world/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/photo.jpg">
      <meta itemprop="name" content="xuarmy">
      <meta itemprop="description" content="木を植える一番いい時間は十年前、次は今です。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="代号·破局">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2020/08/01/hello-world/" class="post-title-link" itemprop="url">开 篇</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-08-01 17:06:13" itemprop="dateCreated datePublished" datetime="2020-08-01T17:06:13+08:00">2020-08-01</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-08-02 12:47:28" itemprop="dateModified" datetime="2020-08-02T12:47:28+08:00">2020-08-02</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>「三十而已」王漫妮说：最先感觉三十岁将至的，也许不是我们的身体，也不是精神，而是物质，比起情感的不安，物质的困顿，才时时刻刻勒着你的脖子，没有了二十岁的洒脱肆意，没有过四十岁的风轻云淡。三十，想要的是更好地生活。</p>
<p>很遗憾十年前我没有种下这棵树，那就现在吧！</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="xuarmy"
      src="/blog/images/photo.jpg">
  <p class="site-author-name" itemprop="name">xuarmy</p>
  <div class="site-description" itemprop="description">木を植える一番いい時間は十年前、次は今です。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">4</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xuarmy</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
